package flextv.main.logic {

import flextv.core.logic.Logger;
import flextv.core.logic.ResponderAdapter;
import flextv.core.vo.Playlist;
import flextv.core.vo.StoredItem;
import flextv.search.vo.SearchItem;

import mx.logging.ILogger;
import mx.utils.ObjectUtil;
	

public class WatchIdImporter {
	
	private static const LOG: ILogger = Logger.getLog(WatchIdImporter);
	
	/**
	 * id in url; stored in IItem.yid
	 */
	private var watchId: String;
	
	private var targetPlaylist: Playlist;
	
	
	public function WatchIdImporter(watchId: String, targetPlaylist: Playlist) {
		if(watchId == null) throw new ArgumentError("watchId == null");
		if(watchId.length == 0) throw new ArgumentError("watchId.length == 0");
		if(targetPlaylist == null) throw new ArgumentError("targetPlaylist == null");
		
		this.watchId = watchId;
		this.targetPlaylist = targetPlaylist;
	}
	
	public function doImport(): void {
		LOG.info("doImport() watchId=["+watchId+"] invoked");
		
		// create new storable value object
		MainServices.instance.singleSearchItemService.fetchNewSearchItemByYid(this.watchId, new ResponderAdapter(
			function(result: Object): void {
				
				const searchItem: SearchItem = SearchItem(result);
				const newStoredItem: StoredItem = searchItem.toStoredItem();
				
				// delegate to AddItemDelegate
				MainServices.instance.addItemService.downloadAddItem(newStoredItem, targetPlaylist, searchItem.thumbnailUrl);
			},
			function(faultInfo: Object): void {
				LOG.error("Unhandled error; watchId["+watchId+"] ... " + faultInfo);
				throw new Error(ObjectUtil.toString(faultInfo));					

			}
		));
		
		
	}

}
}